package club.dmyang.controller;

import club.dmyang.common.enums.RespCodeEnums;
import club.dmyang.common.vo.CategoryVo;
import club.dmyang.common.vo.ResposeVo;
import club.dmyang.entity.Category;
import club.dmyang.service.ArticleService;
import club.dmyang.service.CategoryService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by brss on 2018/7/25.
 */
@Controller
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/listAll")
    @ResponseBody
    public ResposeVo listAll(){
        try {
            //从缓存中读
            String categoryListall = redisTemplate.opsForValue().get("category_listall");
            if ( categoryListall != null ){
                ResposeVo resposeVo = JSON.parseObject(categoryListall, ResposeVo.class);
                return resposeVo;
            }
        } catch (Exception e) {
            e.printStackTrace();
            //无法读缓存时也不能影响正常业务
        }

        //返回给模版的List
        List<CategoryVo> categoryVoList = new ArrayList<>();
        List<Category> categoryList = categoryService.findAll();

        for (Category c : categoryList) {
            //查询某分类下的文章个数
            Integer num = articleService.findNumByCategoryId(c.getCid());
            CategoryVo categoryVo = new CategoryVo();
            try {
                BeanUtils.copyProperties(categoryVo,c);
            } catch (Exception e) {
                e.printStackTrace();
            }
            categoryVo.setNum(num);
            categoryVoList.add(categoryVo);
        }
        //返回页面结果对象
        ResposeVo resposeVo = new ResposeVo(RespCodeEnums.RESP_CODE_SUCC.getCode(), "查询成功！", 0, categoryVoList);
        //对象转json
        String resposeVoJson = JSON.toJSONString(resposeVo);
        try {
            //写缓存
            redisTemplate.opsForValue().set("category_listall",resposeVoJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //因为不需要分页，所以传回count无意义，故传0
        return resposeVo;
    }
}
